package com.mv.CodeStorage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import beans.UserBean;
import beans.UserBeanValidator;

@Controller
public class UserController {
	
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
	    binder.setValidator(new UserBeanValidator());
	}
	
	@RequestMapping(value = "register", method = RequestMethod.GET)
	public String register(Model model){
		
		model.addAttribute("user", new beans.UserBean());
		
		return "register";
	}
	
	@RequestMapping(value = "doRegister", method = RequestMethod.POST)
	public String registerPost(@Validated @ModelAttribute("user") UserBean user, BindingResult result, Model model){
		
		logger.info(user.getLogin());
		logger.info(result.toString());
		
		// TODO : validace duplicity jmena
		
		if (result.hasErrors()){
			return "register";
		}
		
		Export.CodeStorageContext.CodeStorageFactory.SaveItem(new Models.User(user.getEmail(), user.getLogin(), user.getPass(), false));
		
		return "redirect:/";
	}
}
